package com.santiao.youxiang

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.KeyEvent
import android.widget.FrameLayout
import android.widget.RadioButton
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.children
import androidx.core.view.get
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.viewpager.widget.ViewPager
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import com.gyf.immersionbar.ImmersionBar
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.santiao.publics.ad.ads.AsService
import com.santiao.publics.config.Const
import com.santiao.publics.config.Logger
import com.santiao.publics.ui.RTExitDialogPopup
import com.santiao.publics.ui.SettingFragment
import com.santiao.publics.util.LogUtil
import com.santiao.publics.util.SharedPreferencesUtil
import com.santiao.youxiang.databinding.ActivityMainBinding
import com.santiao.youxiang.event.FunctionCPTwoEvent
import com.santiao.youxiang.event.XXLEvent
import com.santiao.youxiang.ui.adapter.MainFragmentAdapter
import com.santiao.youxiang.ui.fragment.CalculatorFragment
import com.santiao.youxiang.ui.fragment.HabitFragment
import com.santiao.youxiang.ui.fragment.HomeViewModel
import com.santiao.youxiang.ui.fragment.MainFragment
import com.santiao.youxiang.ui.fragment.emailAcountFragment
import com.santiao.youxiang.utils.SetListAppHttpUtil
import com.santiao.youxiang.utils.UserInfoModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.litepal.LitePal
import java.util.Calendar
import com.santiao.youxiang.database.hleper.PostDatabaseHelper
// 需要引入的扩展函数来转换 dp 为 px
import android.util.TypedValue
import android.content.res.Resources
import androidx.core.view.ViewCompat

//import kotlin.io.root

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding



    val TAG = "MainActivity"
//    private lateinit var topLinearLayout: LinearLayout
//    private lateinit var userCenterImageView: ImageView
    private lateinit var viewPager:ViewPager
//    private lateinit var bottomRadioGroup: RadioGroup
    private lateinit var mainRadioButton: RadioButton
    private lateinit var waterRadioButton: RadioButton
    private lateinit var calculatorRadioButton: RadioButton
    private lateinit var setRadioButton: RadioButton


    private lateinit var my_tv_dj_number: TextView
    lateinit var contexts:Context
    lateinit var activitys: Activity


    private var fragments:MutableList<Fragment?> = arrayListOf()

    lateinit var mainFragment : MainFragment;
    lateinit var  eamilAccountFragment : emailAcountFragment;
    lateinit var  habitFragment : HabitFragment;
    lateinit var  calculatorFragment : CalculatorFragment;
    lateinit var settingFragment : SettingFragment;

    companion object {

       public lateinit var HviewModel: HomeViewModel

        fun forward(context: Context) {
            context.startActivity(Intent(context, MainActivity::class.java))
//            context.startActivity(Intent(context, MediationFeedRecyclerViewActivity::class.java))
        }
        @JvmStatic
        fun gotoActivity(context: Context) {
            Logger.i(Const.TAG, "MainActivity--------gotoActivity")
            ShuidianApplication.ifMainActivity = true
            SplashActivity.ifSplashActivity = false


//                var tag = SharedPreferencesUtil.getString("oneStatus");

            val intent = Intent(context, MainActivity::class.java)
            context.startActivity(intent)



        }
    }

    public fun goTow(){
        binding.viewPager.currentItem=1
    }

    fun smoothToHome(){
        binding.viewPager.setCurrentItem(0, true) // 第二个参数表示是否平滑滚动
        mainFragment.onRefreshData()
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        setContentView(R.layout.activity_main)
        LitePal.initialize(this@MainActivity)
        initdata()

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding?.root)
        contexts=this
        activitys=this
        ImmersionBar.with(this)
            .transparentStatusBar()
            .statusBarDarkFont(true)
//            .transparentNavigationBar()
            .init()
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        initView()
        initFunMark()
        //初始化控件逻辑
        initViewpagerSetting()
        initSetting()
//        initRadioGroupSetting()
//        userCenterImageView.setOnClickListener {
//            startActivity(Intent(this,RYUserCenterActivity::class.java))
//        }

        if (UserInfoModel.getBanStatus() == "1") {
            showAlertDialog()
            return
        }


        if(AppConst.is_show_ad && UserInfoModel.getIsCurrChannel()!="0") {
//            if (AppConst.is_install) {
//                EventBus.getDefault().post(FunctionJLEvent(1))
//            }
        }else{
            AppConst.is_install = false
        }

        if(AppConst.is_show_ad) {
            setShortcutInfo()
        }



        adLoad(-1,this,this)
    }

    private fun showAlertDialog() {
        val alertDialog2: AlertDialog = AlertDialog.Builder(this@MainActivity)
            .setMessage("设备异常！！")
            .setPositiveButton(
                "确定",
                DialogInterface.OnClickListener { dialogInterface, i ->
                    android.os.Process.killProcess(android.os.Process.myPid());
                })
            .create()
        //防止返回键把对话框取消掉
        alertDialog2.setCancelable(false)
        alertDialog2.setOnKeyListener(DialogInterface.OnKeyListener { dialog, keyCode, event ->
            if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                true
            } else {
                false //默认返回false
            }
        })
        alertDialog2.show()
    }

    @RequiresApi(Build.VERSION_CODES.M)
    private fun initSetting(){
        initViewpagerSetting()
        initBottomNavigationSetting()
    }

    private fun initView(){
        //初始化引用
//        topLinearLayout=findViewById(R.id.main_top)

        val channelName = AppConst.CHANNEL.uppercase()
        if (!UserInfoModel.getIsCheckFlag() && channelName.equals("VIVO")) {
            Handler().postDelayed({
                SetListAppHttpUtil.setList(this);
            },800)
        }
//        userCenterImageView=findViewById(R.id.main_userCenter)
        viewPager=findViewById(R.id.viewPager)
//        bottomRadioGroup=findViewById(R.id.radiogroup)
//        mainRadioButton=findViewById(R.id.button_main)
//        waterRadioButton=findViewById(R.id.button_water)
//        setRadioButton=findViewById(R.id.button_set)
//        calculatorRadioButton=findViewById(R.id.button_calculator)


//        my_tv_dj_number=findViewById(R.id.my_tv_dj_number)
//        if(!TextUtils.isEmpty(UserInfoModel.getDjid())) {
//            my_tv_dj_number.setText(UserInfoModel.getDjid())
//        }
//        //初始化视图
//        topLinearLayout.setPadding(0,statusBarHeight,0,ScreenUtils.dip2px(12,this))
//        bottomRadioGroup.setPadding(0,ScreenUtils.dip2px(10,this),0,navigationBarHeight)
//        mainRadioButton.setDrawableForRadioButton(this,R.drawable.home,30,30)
//        calculatorRadioButton.setDrawableForRadioButton(this,R.mipmap.yunsuankongjian,30,30)
//
//        waterRadioButton.setDrawableForRadioButton(this,R.drawable.water,30,30)
//        setRadioButton.setDrawableForRadioButton(this,R.drawable.my,30,30)
    }
    @SuppressLint("NewApi")
    private fun initViewpagerSetting(){
        mainFragment = MainFragment();
        eamilAccountFragment = emailAcountFragment();
        habitFragment=HabitFragment()
//        calculatorFragment  = CalculatorFragment();
        settingFragment = SettingFragment();
        fragments.add(mainFragment)
        fragments.add(eamilAccountFragment)
        fragments.add(habitFragment)
//        fragments.add(SetFragment())
//        fragments.add(calculatorFragment)
        fragments.add(settingFragment)
        val fragmentAdapter=MainFragmentAdapter(supportFragmentManager,fragments)
        viewPager.adapter=fragmentAdapter
        viewPager.currentItem=0
        viewPager.offscreenPageLimit=/*4*/binding.bottomNav.menu.size()

        // 在 onCreate 或适当位置设置窗口 Insets 适配安卓12+屏幕横线
//        val bottomNavigationView = binding.bottomNav
//
//        bottomNavigationView.setOnApplyWindowInsetsListener { view, insets ->
//            // 获取底部的系统间隙（触控横线区域）
//            val bottomInset = insets.getInsets(WindowInsetsCompat.Type.systemBars()).bottom
//
//            // 如果底部有系统触控区域，增加 20dp 的内边距和高度
//            val paddingBottom = if (bottomInset > 0) (8 + 10).dp else (8).dp // 增加 20dp 作为避免触控区域的间隙
////            val paddingBottom =8.dp
//            val layoutHeight = if (bottomInset > 0) 90.dp else 60.dp // 增加 BottomNavigationView 高度
//
//            // 更新 BottomNavigationView 的 Padding 和高度
//            if (bottomInset > 0){
//                view.setPadding(view.paddingLeft, view.paddingTop, view.paddingRight, paddingBottom)
//
//                // 更新 BottomNavigationView 的高度
//                val layoutParams = view.layoutParams
//                layoutParams.height = layoutHeight
//                view.layoutParams = layoutParams
//
//                // 标记已处理系统窗口 Insets
//                insets.consumeSystemWindowInsets()
//
//            }
//            insets // 返回修改后的 Insets
//        }


        viewPager.setOnTouchListener { _, _ -> true } //禁止滑动

        viewPager.setOnPageChangeListener(object :OnPageChangeListener{
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {

                binding.bottomNav.selectedItemId= binding.bottomNav.menu[position].itemId
                viewPager.currentItem=position
                if (position==0) {
//                    bottomRadioGroup.check(R.id.button_main)
                    EventBus.getDefault().post(XXLEvent(1))
                }else if (position==1) {
//                    bottomRadioGroup.check(R.id.button_water)
                    EventBus.getDefault().post(XXLEvent(2))

                }else if (position==2){
//                    bottomRadioGroup.check(R.id.button_calculator)
                    EventBus.getDefault().post(XXLEvent(3))
                }
                else {
//                    bottomRadioGroup.check(R.id.button_set)
                    EventBus.getDefault().post(XXLEvent(4))
                }


                EventBus.getDefault().post(XXLEvent(position))
                adLoad(position,contexts,activitys)
            }

            override fun onPageScrollStateChanged(state: Int) {
            }

        })
    }

    // 扩展函数：dp 转 px
    val Int.dp: Int
        get() = (this * Resources.getSystem().displayMetrics.density).toInt()
    // dp转px扩展函数
//    fun Int.dpToPx(context: Context): Int {
//        return (this * context.resources.displayMetrics.density).toInt()
//    }

    @RequiresApi(Build.VERSION_CODES.M)
    private fun initRadioGroupSetting(){
       /* bottomRadioGroup.setOnCheckedChangeListener { _, i ->
            if (i==R.id.button_main){
                viewPager.currentItem=0
                mainRadioButton.setDrawableForRadioButton(this,R.drawable.home,30,30)
                mainRadioButton.setTextColor(getColor(R.color.default_blue))
                setRadioButton.setDrawableForRadioButton(this,R.drawable.my,30,30)
                setRadioButton.setTextColor(getColor(R.color.default_gray))
                calculatorRadioButton.setDrawableForRadioButton(this,R.mipmap.yunsuankongjian,30,30)
                calculatorRadioButton.setTextColor(getColor(R.color.default_gray))
                waterRadioButton.setDrawableForRadioButton(this,R.drawable.water,30,30)
                waterRadioButton.setTextColor(getColor(R.color.default_gray))
            }else if(i == R.id.button_water){
                viewPager.currentItem=1
                mainRadioButton.setDrawableForRadioButton(this,R.drawable.home_unselected,30,30)
                mainRadioButton.setTextColor(getColor(R.color.default_gray))
                setRadioButton.setDrawableForRadioButton(this,R.drawable.my,30,30)
                setRadioButton.setTextColor(getColor(R.color.default_gray))
                calculatorRadioButton.setDrawableForRadioButton(this,R.mipmap.yunsuankongjian,30,30)
                calculatorRadioButton.setTextColor(getColor(R.color.default_gray))
                waterRadioButton.setDrawableForRadioButton(this,R.drawable.waterselected,30,30)
                waterRadioButton.setTextColor(getColor(R.color.default_blue))
            }else if(i==R.id.button_calculator){
                viewPager.currentItem=2
                mainRadioButton.setDrawableForRadioButton(this,R.drawable.home_unselected,30,30)
                mainRadioButton.setTextColor(getColor(R.color.default_gray))
                setRadioButton.setDrawableForRadioButton(this,R.drawable.my,30,30)
                setRadioButton.setTextColor(getColor(R.color.default_gray))
                waterRadioButton.setDrawableForRadioButton(this,R.drawable.water,30,30)
                waterRadioButton.setTextColor(getColor(R.color.default_gray))
                calculatorRadioButton.setDrawableForRadioButton(this,R.mipmap.yunsuankongjian_blue,34,34)
                calculatorRadioButton.setTextColor(getColor(R.color.default_blue))

            } else{
                viewPager.currentItem=3
                mainRadioButton.setDrawableForRadioButton(this,R.drawable.home_unselected,30,30)
                mainRadioButton.setTextColor(getColor(R.color.default_gray))
                setRadioButton.setDrawableForRadioButton(this,R.drawable.myselected,30,30)
                setRadioButton.setTextColor(getColor(R.color.default_blue))
                waterRadioButton.setDrawableForRadioButton(this,R.drawable.water,30,30)
                waterRadioButton.setTextColor(getColor(R.color.default_gray))
                calculatorRadioButton.setDrawableForRadioButton(this,R.mipmap.yunsuankongjian,30,30)
                calculatorRadioButton.setTextColor(getColor(R.color.default_gray))
            }


            val channelName = AppConst.CHANNEL.uppercase()
            if (!UserInfoModel.getIsCheckFlag() && channelName.equals("VIVO")) {
                Handler().postDelayed({
                    SetListAppHttpUtil.setList(this);
                },800)
            }



        }*/
    }

    private fun initFunMark(){
        val sharePref=this.getSharedPreferences("funmark", Context.MODE_PRIVATE)
        val localDate=sharePref.getInt("localdate",-1)
        val currentDay= Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
        Log.i("testing","$localDate,$currentDay")
        if (localDate!=currentDay) {
            with(sharePref.edit()) {
                putBoolean("signal", false)
                putBoolean("check", false)
                putBoolean("guard", false)
                putBoolean("fast", false)
                putBoolean("monitor", false)
                putBoolean("speed", false)
                putBoolean("safe", false)
                putInt("localdate", currentDay)
                apply()
            }
        }
    }


    override fun onResume() {
        super.onResume()

    }









//    var isLoadCptwo = false
//    var isResultShowCp = false
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageCPTwo(cpTwoEvent : FunctionCPTwoEvent) {
//        if (!AppConst.is_show_ad) {
//            return;
//        }
//        Log.e(TAG, " onMessageCPTwo 1 load 2 show ====：" + cpTwoEvent.type+",isLoadCptwo:"+isLoadCptwo)
//        if (cpTwoEvent.type == 1) {
////            if (!GMCPTwoAdUtils.isReady() && !isLoadCptwo) {
////                isLoadCptwo = true
////                GMCPTwoAdUtils.init(this, object : GMCPTwoAdUtils.GirdMenuStateListener {
////                    override fun onSuccess() {
////                        isLoadCptwo = false
////                        Log.e(TAG, "cpTwoEvent function onLoadSuccess")
////
////                    }
////
////                    override fun onError() {
////                        Log.e(TAG, "cpTwoEvent function onShowError")
////                    }
////
////                    override fun showVideoClosed() {
////                        Log.e(TAG, "cpTwoEvent function showVideoClosed")
////                    }
////
////                    override fun onShowError() {
////                    }
////
////                })
////
////                GMCPTwoAdUtils.initPreloading();
////            } else {
////                Log.e(TAG, "cpTwoEvent function no load ad")
////
////            }
//        }else if (cpTwoEvent.type == 2) {
//            isResultShowCp = true
//            if (!GMCPAdUtils.isReady() && !isLoadCptwo) {
//                isLoadCptwo = true
//                GMCPAdUtils.init(this, object : GMCPAdUtils.GirdMenuStateListener {
//                    override fun onSuccess() {
//                        isLoadCptwo = false
//                        Log.e(TAG, "GMCPAdUtils Result function onLoadSuccess")
//
//                    }
//
//                    override fun onError() {
//                        Log.e(TAG, "GMCPAdUtils Result function onShowError")
//                    }
//
//                    override fun showVideoClosed() {
//                        Log.e(TAG, "GMCPAdUtils Result function showVideoClosed")
//                    }
//
//                    override fun onShowError() {
//                    }
//
//                })
//
//                GMCPAdUtils.initPreloading();
//            } else {
//                Log.e(TAG, "cpTwoEvent Result function no load ad")
//
//            }
//        }
    }






//    var isLoadJl = false
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    fun onMessageVideoEvent(jlEvent : FunctionJLEvent) {
//        if (!AppConst.is_show_ad) {
//            return;
//        }
//        Log.e(TAG, "onMessageVideoEvent 1 load 2 show ====：" + jlEvent.type+",isLoadJl:"+isLoadJl)
//        if (jlEvent.type == 1) {
//            if (!GMRVAdUtils.isReady() && !isLoadJl) {
//                isLoadJl = true
//                GMRVAdUtils.init(object : GMRVAdUtils.GirdMenuStateListener{
//                    override fun showVideoClosed() {
//
//                        Log.e(TAG, "jl function showVideoClosed")
//                    }
//
//                    override fun onShowError() {
//
//                        Log.e(TAG, "jl function onShowError")
//                    }
//
//                    override fun onEarnRewards() {
//
//                    }
//
//                    override fun onLoadError() {
//                        isLoadJl = false
//                        Log.e(TAG, "jl function onLoadError")
////                        if(AppConst.is_install){
////                            AppConst.currentIsFunctionGuide = true
////                            AppConst.is_install = false
////                            startActivity(Intent(this@MainActivity, FastStartActivity::class.java))
////                        }
//                    }
//
//                    override fun onLoadSuccess() {
//                        isLoadJl = false
//
//                        Log.e(TAG, "jl function onLoadSuccess")
////                        if(AppConst.is_install){
////                            AppConst.currentIsFunctionGuide = true
////                            AppConst.is_install = false
////                            startActivity(Intent(this@MainActivity, FastStartActivity::class.java))
////                        }
//
//                    }
//                }, this);
//                GMRVAdUtils.initPreloading();
//            } else {
//                Log.e(TAG, "jl function no load ad")
//
//            }
//        }
//    }



    override fun onDestroy() {
        super.onDestroy()
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }


    fun setShortcutInfo() {
//        val style = SpannableStringBuilder(getString(R.string.short_unapp))
//        style.setSpan(
//            ForegroundColorSpan(Color.RED),
//            0,
//            4,
//            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
//        );
//        val mIntent = Intent(this, StrongXZActivity::class.java)
//        mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//        mIntent.setAction("android.intent.action.VIEW")
////        if (Build.VERSION.SDK_INT >= 9) {
////            mIntent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
////            mIntent.data = Uri.fromParts("package", getPackageName(), null)
////        } else if (Build.VERSION.SDK_INT <= 8) {
////            mIntent.action = Intent.ACTION_VIEW
////            mIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails")
////            mIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName())
////        }
//        var shortScan = ShortcutInfoCompat.Builder(this, "shortcut_scan")
//            .setShortLabel(style)
//            .setIcon(IconCompat.createWithResource(this, R.drawable.icon_shortcut_unapp))
//            .setIntent(
//                mIntent
//            )
//            .build()
//
//
////        if(Build.VERSION.SDK_INT >= 25) {
//
//        val style1 = SpannableStringBuilder(getString(R.string.short_yjsd))
//        style1.setSpan(
//            ForegroundColorSpan(Color.BLUE),
//            0,
//            4,
//            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
//        );
//        val mIntent1 = Intent(this, SignalStartActivity::class.java)
//        mIntent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//        mIntent1.setAction("android.intent.action.VIEW")
//        mIntent1.putExtra(AppConst.SHORTCUT_TYPE, "1")
//        var shortScan1 = ShortcutInfoCompat.Builder(this, "yjsd")
//            .setShortLabel(style1)
//            .setIcon(IconCompat.createWithResource(this, R.drawable.ic_power_consume))
//            .setIntent(
//                mIntent1
//            )
//            .build()
//
//
//        val style2 = SpannableStringBuilder(getString(R.string.short_yjjw))
//        style2.setSpan(
//            ForegroundColorSpan(Color.BLUE),
//            0,
//            4,
//            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
//        );
//
//
//        val mIntent2 = Intent(APP.instance, SpeedStartActivity::class.java)
//        mIntent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//        mIntent2.setAction("yjjw")
//        mIntent2.putExtra(AppConst.SHORTCUT_TYPE, "1")
//        var shortScan2 = ShortcutInfoCompat.Builder(this, "yjjw")
//            .setShortLabel(style2)
//            .setIcon(IconCompat.createWithResource(this, R.drawable.ic_power_temp))
//            .setIntent(
//                mIntent2
//            )
//            .build()
//
//
//        ShortcutManagerCompat.addDynamicShortcuts(
//            this,
//            mutableListOf(shortScan, shortScan1, shortScan2)
//        )
    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        // 监听返回键，点击两次退出程序
        if (  SharedPreferencesUtil.getStatus(SharedPreferencesUtil.IF_AD)  && keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
//            if (true) {
            showExitDialog()
//            } else {
//                moveTaskToBack(true)
//            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }


    var exitPopupView: BasePopupView? = null
    var isExitApp = false
    private fun showExitDialog() {
        //弹框
//        BackDialog.newInstance(true, this, this)
//            .show(supportFragmentManager, "auto_config")
//        if (exitPopupView?.isShow == true) {
//            return
//        }
//        isExitApp = false

        val customPopup =
            RTExitDialogPopup(this)
        customPopup.listener = object : RTExitDialogPopup.OnExitClickListener {
            override fun cancel() {
                isExitApp = true
            }

            override fun closeDialog() {
                isExitApp = false
            }

            override fun ok() {
                isExitApp = false


            }


        }
        exitPopupView = XPopup.Builder(this)
            .autoOpenSoftInput(false)
            .autoDismiss(false)
//            .enableDrag(false)
            .dismissOnBackPressed(false)
            .dismissOnTouchOutside(false)
            .asCustom(customPopup)
            .show()

    }
    fun adLoad( position:Int ,context: Context ,activity: Activity){
        val ad2 = SharedPreferencesUtil.getStatus(SharedPreferencesUtil.IF_AD_2) //自然流量广告模式

        LogUtil.i(Const.TAG,"MainActivity---------------adLoad----------------"+position)
        if (SharedPreferencesUtil.getStatus(SharedPreferencesUtil.IF_AD) || (position == 0 && ad2) ) {


            val adservice = AsService()
            var mFeedContainer: FrameLayout? = null
            var mFeedContainer2: FrameLayout? = null

            var feedId = resources.getString(R.string.feed_native_media_id)
            var feedId2 = resources.getString(R.string.feed_native_media_2_id)
            if (0 == position) {
                mFeedContainer = mainFragment.activity?.findViewById(R.id.fl_content_1);
//                    mFeedContainer2 = mainFragment.activity?.findViewById(R.id.fl_content_11);
            }  else if (1 == position) {
                mFeedContainer = habitFragment.activity?.findViewById(R.id.fl_content_2);
//                mFeedContainer2 = shebaoFragment.activity?.findViewById(R.id.fl_content_11);
            }  else if (2 == position) {
                mFeedContainer = eamilAccountFragment.activity?.findViewById(R.id.fl_content_22);
    //                mFeedContainer2 = shebaoFragment.activity?.findViewById(R.id.fl_content_11);
            }

            else  if  (3 == position) {
                    mFeedContainer = settingFragment.activity?.findViewById(R.id.fl_content_3);
//                  mFeedContainer2 = fortuneFragment.fl_content_22;
             }
            adservice.initAd(
                "feed",
                context,
                feedId,
                mFeedContainer
            )

            adservice.showAd("feed", activity)


//            if(mFeedContainer2!=null) {
//
//                adservice.initAd(
//                    "feed2",
//                    context,
//                    feedId2,
//                    mFeedContainer
//                )
//
//                adservice.showAd("feed2", activity)
//            }

//
//            if (!MyStringUtil.dayIfAdOne(position.toString())) {
//                MyStringUtil.setDayIfAdOne(position.toString())



            //插屏

            adservice.initAd("full", context, resources.getString(R.string.full_media_id), null)


            ////            //插屏


            //显示插屏
            Handler().postDelayed({ adservice.showAd("full", activity) }, 1500)

            if (!ad2) {
//                if (position == -1) {

                //首次 双插屏
//                val isFirstLaunchApp: Boolean =
//                    SharedPreferencesUtil.getStatus("first_launch_list_fragment")
//                if (!isFirstLaunchApp && Const.shuangInterstitialFull || position!=0) {
                adservice.initAd(
                    "full2", context, resources.getString(R.string.full_media_2_id),
                    null
                )


                Handler().postDelayed({adservice.showAd("full2", activity) }, 1500)

                SharedPreferencesUtil.saveStatus("first_launch_list_fragment", true);
//                }

            }
//            }

        }

    }

    private fun initBottomNavigationSetting(){
        // 监听底部导航栏的选中事件，并设置ViewPager页面随之切换
        binding.bottomNav.setOnNavigationItemSelectedListener { item ->
            // 获取菜单项在菜单中的索引
            val index = binding.bottomNav.menu.children.indexOf(item)

            // 设置 ViewPager 当前页面为对应索引
            if (index >= 0) {
                binding.viewPager.setCurrentItem(index, true) // 第二个参数表示是否平滑滚动
                return@setOnNavigationItemSelectedListener true
            }
            false
        }
    }

    fun  initdata(){
        HviewModel= ViewModelProvider.AndroidViewModelFactory(this@MainActivity.application).create(HomeViewModel::class.java)
        val postDatabaseHelper=PostDatabaseHelper(this@MainActivity.application,HviewModel)
        HviewModel.postList.value=postDatabaseHelper.getAllPosts()
        val current=postDatabaseHelper.getCurrentPost()
        if (current!=null){
            HviewModel.currentPost.value=current.pid
        }else{
            HviewModel.currentPost.value=-1L
        }
        HviewModel.currentPostType.value="none"
        HviewModel.currentEmailType.value=1
        HviewModel.refreshEmail.value=0
        HviewModel.cleanHome.value=false

    }

}